package com.hmkj.core.service.system.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.core.constant.Enum;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.invest.InvestMapper;
import com.hmkj.core.mapper.seller.SellerMapper;
import com.hmkj.core.mapper.system.AdminMapper;
import com.hmkj.core.mapper.system.RoleMapper;
import com.hmkj.core.mapper.user.UserMapper;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.invest.Invest;
import com.hmkj.core.po.seller.Seller;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.po.system.Role;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.system.AdminService;
import com.xiaoleilu.hutool.crypto.digest.DigestUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员账号业务相关Service接口实现<br>
 *
 * @author donfy
 * @ClassName: AdminServiceImpl
 * @date 2017-08-16 08:18:00
 */
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private InvestMapper investMapper;

    @Resource
    private SellerMapper sellerMapper;

    @Override
    public Admin saveAdmin(Admin admin) throws BussinessException {
        Integer roleId = admin.getRoleId();
        if (roleId == null || roleId <= 0) {
            throw new BussinessException("请选择管理员角色");
        }
        Role role = roleMapper.selectByPrimaryKey(roleId);
        if (role == null) {
            throw new BussinessException("您选择的角色不存在或已删除，请重新选择");
        }
        admin.setRoleName(role.getName());
        admin.setPassword(DigestUtil.md5Hex(admin.getPassword()));
        admin.setCreateTime(new Date());
        admin.setDelFlag(Admin.DELFLAG.NORMAL.code);
        int i = adminMapper.insert(admin);
        if (i != 1) throw new BussinessException("保存失败!");
        return admin;
    }

    @Override
    public void updateAdmin(Admin admin) throws BussinessException {
        Integer roleId = admin.getRoleId();
        if (roleId == null || roleId <= 0) {
            throw new BussinessException("请选择管理员角色");
        }
        Role role = roleMapper.selectByPrimaryKey(roleId);
        if (role == null) {
            throw new BussinessException("您选择的角色不存在或已删除，请重新选择");
        }
        admin.setRoleName(role.getName());
        admin.setPassword(DigestUtil.md5Hex(admin.getPassword()));
        this.updateByPrimaryKeySelective(admin);
    }

    @Override
    public Admin getAdminById(Integer id) throws BussinessException {
        return this.selectByPrimaryKey(id);
    }

    @Override
    public void addAdminInvest(User user, BigDecimal feeScale) {
        //修改user表的用户类型为投资人
        userMapper.updateByPrimaryKeySelective(new User(t -> {
            t.setId(user.getId());
            t.setUserType(Enum.UserType.INVESTOR.getValue());
        }));
        //用户id，手机号码，用户名，姓名，投资比例
        //添加投资人信息
        investMapper.insert(new Invest(t -> {
            t.setUserId(user.getId());
            t.setFeeScale(feeScale.divide(BigDecimal.valueOf(10000)));
            t.setStatus(Invest.STATUS.T1.code);
            t.setInvestAccount(BigDecimal.ZERO);
            t.setReceiveCount(0);
        }));
        //添加投资人信息
        adminMapper.insert(new Admin(t -> {
            t.setRoleId(Enum.INVEST_ROLE_ID);
            t.setRoleName(Enum.INVEST_ROLE_NAME);
            t.setPassword(user.getPassword());
            //用户名
            t.setName(user.getMobilePhone());
            t.setType(Enum.INVEST_TYPE);
            t.setUserId(user.getId());
        }));

    }

    /**
     * 添加销售
     *
     * @param user
     */
    public void addAdminSeller(UserModel user, Admin admin) throws BussinessException {

        //校验上级
        Integer level = user.getLevel();
        Integer parentId = user.getInviteId();
        Integer userType = user.getUserType();
        User parentUser = null;

        if (level > 1) {
            //检验上级
            for (int i = level - 1; i >0; i--) {
                parentUser = userMapper.selectByPrimaryKey(parentId);
                Integer p = parentUser.getUserType();
                if (p == Enum.UserType.NEXTSELLER.getValue()) {
                    throw new BussinessException("添加的用户上级不能存在低于或同于当前添加的销售类型的用户");
                }
                if (userType == Enum.UserType.ONELEVEL.getValue()) {
                    if (p == Enum.UserType.ONELEVEL.getValue() || p == Enum.UserType.TWOLEVEL.getValue() || p == Enum.UserType.THREELEVEL.getValue()) {
                        throw new BussinessException("添加的用户上级不能存在低于或同于当前添加的销售类型的用户");
                    }
                }
                if (userType == Enum.UserType.TWOLEVEL.getValue()) {
                    if (p == Enum.UserType.TWOLEVEL.getValue() || p == Enum.UserType.THREELEVEL.getValue()) {
                        throw new BussinessException("添加的用户上级不能存在低于或同于当前添加的销售类型的用户");
                    }
                }
                if (userType == Enum.UserType.THREELEVEL.getValue()) {
                    if (p == Enum.UserType.THREELEVEL.getValue()) {
                        throw new BussinessException("添加的用户上级不能存在低于或同于当前添加的销售类型的用户");
                    }
                }
                parentId = parentUser.getInviteId();
                userType = parentUser.getUserType();
            }
        }

        //校验下级
        Map<String, Object> param = new HashMap<>();
        param.put("code", user.getCode());
        param.put("level", null);
        List<User> userList = userMapper.listPartnerByLevel(param);
        for (User n : userList) {
            Integer t = n.getUserType();
            if (t == Enum.UserType.AGENTSELLER.getValue() || t == Enum.UserType.NEXTSELLER.getValue() || t == Enum.UserType.ONELEVEL.getValue() || t == Enum.UserType.TWOLEVEL.getValue() || t == Enum.UserType.THREELEVEL.getValue()) {
                throw new BussinessException("添加的用户下级不能存在代理商或者销售");
            }
        }

        userMapper.updateByPrimaryKeySelective(user);
        //用户id，手机号码，用户名，姓名
        //添加销售信息
        sellerMapper.insert(new Seller(r -> {
            r.setUserId(user.getId());
            r.setStatus(String.valueOf(Enum.Status.ON.getValue()));
            r.setAllCustomer(user.getAllCustomer());
            r.setCustomerPhone(user.getCustomerPhone());
            r.setFeeScale(user.getFeeScale().divide(BigDecimal.valueOf(10000)));
        }));
        //添加投资人信息
        Admin admin1 = new Admin();
        if (user.getUserType() == Enum.UserType.NEXTSELLER.getValue()) {
            admin1.setRoleId(Enum.NEXT_SELLER_ROLE_ID);
            admin1.setRoleName(Enum.NEXT_SELLER_ROLE_NAME);
            admin1.setType(Enum.NEXT_SELLER_TYPE);
        } else if (user.getUserType() == Enum.UserType.AGENTSELLER.getValue()) {
            admin1.setRoleId(Enum.AGENT_SELLER_ROLE_ID);
            admin1.setRoleName(Enum.AGENT_SELLER_ROLE_NAME);
            admin1.setType(Enum.AGENT_SELLER_TYPE);
        }
        admin1.setPassword(user.getPassword());
        //用户名
        admin1.setName(user.getMobilePhone());
        admin1.setUserId(user.getId());
        admin1.setStatus(Integer.valueOf(Enum.Status.ON.getValue()));
        adminMapper.insert(admin1);
    }

    @Override
    public GenericMapper<Admin, Integer> _getMapper() {
        return adminMapper;
    }

}
